//
//  WKLoginViewController.m
//  Walk
//
//  Created by cesh on 16/9/2.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKLoginViewController.h"
#import "WKBubbleViewController.h"
#import "WKEditViewController.h"
#import <UIImageView+WebCache.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"
#import <UMSocialCore/UMSocialCore.h>
#import <AFNetworking.h>
#import <SVProgressHUD.h>

@interface WKLoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *verificationTextField;
@property (weak, nonatomic) IBOutlet UIButton *getVertificationBtn;

@property (strong, nonatomic) NSTimer *countDownTimer;

@property (assign, nonatomic) NSInteger currentDownloadedPicCount;
@property (weak, nonatomic) IBOutlet UIView *registerProtocol;

@property (weak, nonatomic) IBOutlet UILabel *thirdLoginLbl;
@property (weak, nonatomic) IBOutlet UIButton *weChatBtn;
@property (weak, nonatomic) IBOutlet UIButton *QQBtn;
@end

@implementation WKLoginViewController

NSInteger count = COUNTDOWN;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentDownloadedPicCount = 0;
    //点击背景退出键盘
    UITapGestureRecognizer *tapOnBg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resighKeyboard)];
    [self.view addGestureRecognizer:tapOnBg];
    //获取验证码的按钮事件
    [self.getVertificationBtn addTarget:self action:@selector(clickVertificationBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openRegisterProcal)];
    [self.registerProtocol addGestureRecognizer:tap];
    //判断QQ是否安装
    if (![QQApiInterface isQQInstalled]) {
        self.QQBtn.hidden = YES;
    }
    //判断微信是否安装
    if (![WXApi isWXAppInstalled]) {
        self.weChatBtn.hidden = YES;
    }
    //如果两者均没安装，隐藏三方登录的label
    if (![QQApiInterface isQQInstalled] && ![WXApi isWXAppInstalled]) {
        self.thirdLoginLbl.hidden = YES;
    }
}

- (void)openRegisterProcal {
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://junvalley.com/walk/Web/registerRules"]];
}

- (void)resighKeyboard {
    [self.phoneTextField resignFirstResponder];
    [self.verificationTextField resignFirstResponder];
}

- (void)clickVertificationBtn:(UIButton *)button {
    [self.getVertificationBtn setTitle:[NSString stringWithFormat:@"获取中(%li)", (long)COUNTDOWN] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:0x9b / 255.0 green:0x9b / 255.0 blue:0x9b / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setEnabled:NO];
    self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
}

- (void)countDown {
    count--;
    [self.getVertificationBtn setTitle:[NSString stringWithFormat:@"获取中(%li)", (long)count] forState:UIControlStateNormal];
    //事件倒数为0则重置
    if (count == -1) {
        [self.getVertificationBtn setEnabled:YES];
        [self.getVertificationBtn setTitleColor:[UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0] forState:UIControlStateNormal];
        [self.getVertificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.countDownTimer invalidate];
        count = COUNTDOWN;
    }
}
- (IBAction)getCode:(id)sender {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    [mgr POST:[NSString stringWithFormat:@"%@Sms/sendCode", URL] parameters:@{@"phone" : self.phoneTextField.text} progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取验证码 %@", responseObject);
        if ([responseObject[@"state"] isEqualToString:@"FAIL"]) {
            [SVProgressHUD showWithStatus:@"手机号码不合法"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        [WKPopView showWithType:PopViewTypeTimeOut];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
        });
    }];
}
- (IBAction)login:(id)sender {
    
    [self.countDownTimer invalidate];
    self.countDownTimer = nil;
    [self resighKeyboard];
    //拦截电话号码为空的情况
    if ([self.phoneTextField.text length] == 0 || [self.verificationTextField.text length] == 0) {
        return;
    }
    
    [WKPopView showWithType:PopViewTypeLoading];
    //发送登录请求，获取环信的用户名密码
    NSDictionary *dict = @{
                           @"phone" : self.phoneTextField.text,
                           @"code" : self.verificationTextField.text,
                           };
    [self loginWithDict:dict phone:YES];
}

- (IBAction)thirdLogin:(UIButton *)sender {
    //根据按钮的tag判断是qq还是微信登陆
    UMSocialPlatformType socialPlatformType;
    if (sender.tag == 1) {
        socialPlatformType = UMSocialPlatformType_QQ;
    }
    else {
        socialPlatformType = UMSocialPlatformType_WechatSession;
    }
    
    [[UMSocialManager defaultManager]authWithPlatform:socialPlatformType currentViewController:self completion:^(id result, NSError *error) {
        UMSocialAuthResponse *authresponse = result;
        if(error.code) {
            [SVProgressHUD showInfoWithStatus:@"登录失败"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        else {
            [self.countDownTimer invalidate];
            self.countDownTimer = nil;
            WKPopView *popV = [WKPopView showWithType:PopViewTypeLoading];
            popV.centerView.y -= screenH * 0.2;
            //发送登录请求，获取环信的用户名密码
            NSDictionary *dict = @{
                                   @"openid" :authresponse.openid,
                                   @"type" : [NSString stringWithFormat:@"%li",(long)sender.tag],
                                   };
            [self loginWithDict:dict phone:NO];
        }
    }];
}

- (void)loginWithDict:(NSDictionary *)dict phone:(BOOL)phone{
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    NSString *postURL = phone ? [NSString stringWithFormat:@"%@Login/codeLogin", URL] : [NSString stringWithFormat:@"%@Login/thirdLogin",URL];
    
    [mgr POST:postURL parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [WKPopView dismiss];
        
        NSLog(@"登录信息%@", responseObject);
        
        if ([responseObject[@"state"] isEqualToString:@"FAIL"]) {
            [SVProgressHUD showInfoWithStatus:responseObject[@"data"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                return;
            });
        }
        else {
            NSString *is_full = responseObject[@"data"][@"is_full"];
            //获取token并存储在本地
            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
            [userInfo setValue:responseObject[@"data"][@"data"][@"token"] forKey:@"token"];
            NSLog(@"登录token %@", responseObject[@"data"][@"data"][@"token"]);
            [userInfo setValue:responseObject[@"data"][@"data"][@"id"] forKey:@"id"];
            [userInfo setValue:responseObject[@"data"][@"data"][@"hx_user"] forKey:@"hx_user"];
            [userInfo setValue:responseObject[@"data"][@"data"][@"hx_pwd"] forKey:@"hx_pwd"];
            [userInfo setValue:responseObject[@"data"][@"data"][@"phone"] forKey:@"phoneNumber"];
            NSLog(@"userinfo %@", userInfo);
            NSLog(@"保存基本userinfo 成功：%i",[userInfo writeToFile:userInfoPath atomically:YES]);
            
            //根据is_full字段是否完整, 判定进入的是哪个界面
            if ([is_full isEqualToString:@"0"]) {
                //is_full字段为0 ，资料不完整，进入个人资料界面
                //如果还没有登录，则进入个人资料界面
                WKEditViewController *bubbleVC = [[WKEditViewController alloc]init];
                CATransition *anim = [CATransition animation];
                anim.type = @"rippleEffect";
                anim.duration = 1.0;
                [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
                [UIApplication sharedApplication].keyWindow.rootViewController = bubbleVC;
            }
            //is_full字段为1，资料完整，把相关数据保存到本地，然后进入气泡界面
            else {
                //userInfo设置
                [userInfo setValue:responseObject[@"data"][@"data"][@"nickname"] forKey:@"nickname"];
                [userInfo setValue:responseObject[@"data"][@"data"][@"sex"] forKey:@"sex"];
                
                NSString *birthday = responseObject[@"data"][@"data"][@"birthday"];
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:[birthday integerValue]];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy/MM/dd"];
                NSString *strDate = [dateFormatter stringFromDate:date];
                [userInfo setValue:strDate forKey:@"birthday"];
                
                [userInfo setValue:responseObject[@"data"][@"data"][@"describe"] forKey:@"describe"];
                [userInfo setValue:responseObject[@"data"][@"data"][@"school"][@"name"] forKey:@"school"];
                [userInfo setValue:responseObject[@"data"][@"data"][@"major"][@"name"] forKey:@"major"];
                NSLog(@"保存基本userinfo 成功：%i",[userInfo writeToFile:userInfoPath atomically:YES]);
                NSLog(@"is_full为1的时候  %@",userInfo);
                //保存图片
                //1.获取所有图片的url
                NSString *headImgURL = responseObject[@"data"][@"data"][@"headerImg"][@"url"];
                NSArray *otherImgs = responseObject[@"data"][@"data"][@"otherImg"];
                //2.将所有图片的url保存到数组中
                NSMutableArray *imgsURLs = [NSMutableArray array];
                [imgsURLs addObject:headImgURL];
                for (NSDictionary *otherImg in otherImgs) {
                    [imgsURLs addObject:otherImg[@"url"]];
                }
                //3.根据取到的url读取图片并保存到本地
                NSMutableArray *imgsLocal = [NSMutableArray array];
                for (NSString *imgUrl in imgsURLs) {
                    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imgUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                        
                    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                        if (error) {
                            NSLog(@"下载图片失败 %@",error);
                        }
                        if (image) {
                            //图片下载完成  在这里进行相关操作，如加到数组里 或者显示在imageView上
                            NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
                            [imgsLocal addObject:imgData];
                            self.currentDownloadedPicCount++;
                            if (self.currentDownloadedPicCount == [imgsURLs count]) {
                                [imgsLocal writeToFile:userImagesPath atomically:YES];
                            }
                        }
                    }];
                }
                
                [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"didLogin"];
                WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
                CATransition *anim = [CATransition animation];
                anim.type = @"rippleEffect";
                anim.duration = 1.0;
                [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
                
                [UIApplication sharedApplication].keyWindow.rootViewController = bubbleVC;
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        [WKPopView showWithType:PopViewTypeTimeOut];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
        });
    }];
}
@end
